package com.lwm.service.impl;

import com.lwm.domain.User;
import com.lwm.domain.LoginUser;
import com.lwm.mapper.UserMapper;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * 用户信息查询切换
 * 内存查询 → 数据库查询
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Resource
    private UserMapper userMapper;
    /**
     * 根据用户名加载用户
     *
     * @param username 用户名
     * @return {@link UserDetails}
     * @throws UsernameNotFoundException 用户名没有找到异常
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userMapper.selectUserByUsername(username);
        // 查询的用户信息为空
        if (Objects.isNull(user)) throw new RuntimeException("用户名或密码错误");

        // TODO 根据用户名查询用户权限信息 添加到LoginUser中 (后面可能不会去做授权功能吧)

        // 封装成UserDetails对象返回
        return new LoginUser(user);
    }
}
